package com.bear.atlassianmcp.jira.mcp.tools;

import com.bear.atlassianmcp.jira.model.JiraSearchResult;
import com.bear.atlassianmcp.jira.service.JiraService;
import com.bear.atlassianmcp.jira.service.JqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 搜索MCP工具
 * 提供各种Jira搜索功能
 */
@Service
public class SearchTools {

    private static final Logger logger = LoggerFactory.getLogger(SearchTools.class);

    private final JiraService jiraService;

    @Autowired
    public SearchTools(JiraService jiraService) {
        this.jiraService = jiraService;
    }

    /**
     * 使用JQL搜索Issues
     *
     * @param jql JQL查询语句
     * @param maxResults 最大结果数，默认50
     * @param context 工具上下文
     * @return 搜索结果的格式化文本
     */
    @Tool(description = "使用JQL(Jira Query Language)搜索Issues，支持复杂的查询条件，如'project = PROJ AND status = Open'")
    public String searchIssues(@ToolParam(description = "JQL查询语句，如'project = PROJ AND status = Open'，支持复杂条件组合") String jql,
                              @ToolParam(required = false, description = "最大结果数，默认50，建议不超过100") Integer maxResults,
                              ToolContext context) {
        logger.info("MCP Tool: Searching issues with JQL: {}", jql);

        try {
            JiraSearchResult result = jiraService.searchIssues(jql, maxResults, context);
            String formattedResult = result.toFormattedString();

            logger.info("Successfully searched issues via MCP: found {} results", result.getTotal());
            return formattedResult;

        } catch (Exception e) {
            logger.error("Failed to search issues via MCP: {}", e.getMessage());
            return "❌ 搜索失败。原因：" + e.getMessage() +
                   "\n💡 提示：请检查JQL语法是否正确，常用格式如：project = PROJ AND status = Open";
        }
    }

    /**
     * 获取当前用户分配的Issues
     *
     * @param context 工具上下文
     * @return 当前用户的Issues列表
     */
    @Tool(description = "获取Jira分配给当前登录用户的所有Issues，按更新时间倒序排列")
    public String getMyIssues(ToolContext context) {
        logger.info("MCP Tool: Getting my issues");

        try {
            JiraSearchResult result = jiraService.getMyIssues(context);

            if (result.getTotal() == 0) {
                return "📋 您当前没有分配的Issues。";
            }

            String formattedResult = "👤 您的Issues：\n" + result.toFormattedString();

            logger.info("Successfully retrieved my issues via MCP: {} issues", result.getTotal());
            return formattedResult;

        } catch (Exception e) {
            logger.error("Failed to get my issues via MCP: {}", e.getMessage());
            return "❌ 获取我的Issues失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取最近N天更新的Issues
     *
     * @param days 天数，默认7天
     * @param context 工具上下文
     * @return 最近更新的Issues列表
     */
    //@Tool(description = "获取Jira最近N天内更新的Issues，默认7天，按更新时间倒序排列")
    public String getRecentIssues(Integer days, ToolContext context) {
        int searchDays = days != null ? days : 7;
        logger.info("MCP Tool: Getting recent issues for {} days", searchDays);

        try {
            JiraSearchResult result = jiraService.getRecentIssues(searchDays, context);

            if (result.getTotal() == 0) {
                return String.format("📅 最近%d天没有更新的Issues。", searchDays);
            }

            String formattedResult = String.format("📅 最近%d天更新的Issues：\n%s",
                                                  searchDays, result.toFormattedString());

            logger.info("Successfully retrieved recent issues via MCP: {} issues in {} days",
                       result.getTotal(), searchDays);
            return formattedResult;

        } catch (Exception e) {
            logger.error("Failed to get recent issues via MCP: {}", e.getMessage());
            return "❌ 获取最近Issues失败。原因：" + e.getMessage();
        }
    }

    /**
     * 搜索包含指定文本的Issues
     *
     * @param text 搜索文本
     * @param maxResults 最大结果数，默认20
     * @param context 工具上下文
     * @return 包含指定文本的Issues列表
     */
    @Tool(description = "在Jira Issue的标题、描述、评论中搜索包含指定文本的Issues")
    public String searchByText(@ToolParam(description = "要搜索的文本内容，将在Issue标题、描述、评论中查找") String text,
                              @ToolParam(required = false, description = "最大结果数，默认20") Integer maxResults,
                              ToolContext context) {
        logger.info("MCP Tool: Searching issues by text: {}", text);

        try {
            JiraSearchResult result = jiraService.searchByText(text, context);

            // 限制结果数量
            int limit = maxResults != null ? maxResults : 20;
            if (result.getIssues() != null && result.getIssues().size() > limit) {
                result.getIssues().subList(limit, result.getIssues().size()).clear();
                result.setMaxResults(limit);
            }

            if (result.getTotal() == 0) {
                return String.format("🔍 没有找到包含文本 \"%s\" 的Issues。", text);
            }

            String formattedResult = String.format("🔍 包含文本 \"%s\" 的Issues：\n%s",
                                                  text, result.toFormattedString());

            logger.info("Successfully searched issues by text via MCP: {} results", result.getTotal());
            return formattedResult;

        } catch (Exception e) {
            logger.error("Failed to search issues by text via MCP: {}", e.getMessage());
            return "❌ 文本搜索失败。原因：" + e.getMessage();
        }
    }

    /**
     * 高级搜索：按项目、状态、经办人搜索
     * 
     * @param projectKey 项目键值（可选）
     * @param status 状态（可选）
     * @param assignee 经办人（可选，使用"currentUser"表示当前用户）
     * @param maxResults 最大结果数，默认30
     * @return 搜索结果
     */
    @Tool(description = "Jira高级搜索功能，可以组合项目、状态、经办人等条件进行搜索，参数可选")
    public String advancedSearch(@ToolParam(required = false, description = "项目键值，如PROJ、DEMO等，可选参数") String projectKey,
                                @ToolParam(required = false, description = "Issue状态，如Open、In Progress、Done等，可选参数") String status,
                                @ToolParam(required = false, description = "经办人用户名，使用currentUser表示当前用户，可选参数") String assignee,
                                @ToolParam(required = false, description = "最大结果数，默认30") Integer maxResults,
                                ToolContext toolContext) {
        logger.info("MCP Tool: Advanced search - project: {}, status: {}, assignee: {}", 
                   projectKey, status, assignee);
        
        try {
            JqlBuilder builder = JqlBuilder.create();
            
            if (projectKey != null && !projectKey.trim().isEmpty()) {
                builder.project(projectKey);
            }
            
            if (status != null && !status.trim().isEmpty()) {
                builder.status(status);
            }
            
            if (assignee != null && !assignee.trim().isEmpty()) {
                if ("currentUser".equalsIgnoreCase(assignee)) {
                    builder.assignee("currentUser()");
                } else {
                    builder.assignee(assignee);
                }
            }
            
            String jql = builder.orderByUpdatedDesc().build();
            
            if (jql.trim().isEmpty()) {
                return "❌ 请至少提供一个搜索条件（项目、状态或经办人）。";
            }
            
            JiraSearchResult result = jiraService.searchIssues(jql, maxResults, toolContext);
            
            if (result.getTotal() == 0) {
                return "🔍 没有找到符合条件的Issues。";
            }
            
            String formattedResult = "🔍 高级搜索结果：\n" + result.toFormattedString();
            
            logger.info("Successfully performed advanced search via MCP: {} results", result.getTotal());
            return formattedResult;
            
        } catch (Exception e) {
            logger.error("Failed to perform advanced search via MCP: {}", e.getMessage());
            return "❌ 高级搜索失败。原因：" + e.getMessage();
        }
    }

    /**
     * 搜索高优先级Issues
     *
     * @param projectKey 项目键值（可选）
     * @param context 工具上下文
     * @return 高优先级Issues列表
     */
    // @Tool(description = "搜索高优先级(High/Critical)的Issues，可以指定项目范围")
    public String getHighPriorityIssues(String projectKey, ToolContext context) {
        logger.info("MCP Tool: Getting high priority issues for project: {}", projectKey);

        try {
            JqlBuilder builder = JqlBuilder.create();

            if (projectKey != null && !projectKey.trim().isEmpty()) {
                builder.project(projectKey);
            }

            // 搜索高优先级（根据实际Jira配置调整）
            String jql = builder.build();
            if (!jql.isEmpty()) {
                jql += " AND ";
            }
            jql += "(priority = High OR priority = Highest)";
            jql += " ORDER BY priority DESC, updated DESC";

            JiraSearchResult result = jiraService.searchIssues(jql, 30, context);
            
            if (result.getTotal() == 0) {
                String scope = projectKey != null ? "项目 " + projectKey + " 中" : "";
                return String.format("🚨 %s当前没有高优先级Issues。", scope);
            }
            
            String scope = projectKey != null ? "项目 " + projectKey + " 中的" : "";
            String formattedResult = String.format("🚨 %s高优先级Issues：\n%s", 
                                                  scope, result.toFormattedString());
            
            logger.info("Successfully retrieved high priority issues via MCP: {} issues", result.getTotal());
            return formattedResult;
            
        } catch (Exception e) {
            logger.error("Failed to get high priority issues via MCP: {}", e.getMessage());
            return "❌ 获取高优先级Issues失败。原因：" + e.getMessage();
        }
    }

    /**
     * 搜索未分配的Issues
     *
     * @param projectKey 项目键值（可选）
     * @param context 工具上下文
     * @return 未分配的Issues列表
     */
    // @Tool(description = "搜索未分配经办人的Issues，可以指定项目范围")
    public String getUnassignedIssues(String projectKey, ToolContext context) {
        logger.info("MCP Tool: Getting unassigned issues for project: {}", projectKey);

        try {
            JqlBuilder builder = JqlBuilder.create();

            if (projectKey != null && !projectKey.trim().isEmpty()) {
                builder.project(projectKey);
            }

            String jql = builder.build();
            if (!jql.isEmpty()) {
                jql += " AND ";
            }
            jql += "assignee is EMPTY ORDER BY created DESC";

            JiraSearchResult result = jiraService.searchIssues(jql, 25, context);
            
            if (result.getTotal() == 0) {
                String scope = projectKey != null ? "项目 " + projectKey + " 中" : "";
                return String.format("👤 %s当前没有未分配的Issues。", scope);
            }
            
            String scope = projectKey != null ? "项目 " + projectKey + " 中的" : "";
            String formattedResult = String.format("👤 %s未分配Issues：\n%s", 
                                                  scope, result.toFormattedString());
            
            logger.info("Successfully retrieved unassigned issues via MCP: {} issues", result.getTotal());
            return formattedResult;
            
        } catch (Exception e) {
            logger.error("Failed to get unassigned issues via MCP: {}", e.getMessage());
            return "❌ 获取未分配Issues失败。原因：" + e.getMessage();
        }
    }
}
